<template>
    <div class="issue-list">
        <div class="move-box">
            <RiskLeftModule
                v-model="userValue"
                @on-submit="submitInput"
                @on-handleNode="clickNode"
                :placeholders="ltitleName"
                :treeData="treeData"
                :leftHeight="leftHgt"
                :currentKey="2"
                :defaultExpandedKeys="defaultExpandedKeys"
            >
                <template slot="ltitle">评级机构池信息</template>
            </RiskLeftModule>

            <!-- 评级机构池 -->
            <template v-if="cutInfo === '本地' || cutInfo === '外部'">
                <RiskRightModule v-model="roleInput" :rightPlace="rtitleName" :rightHeight="leftHgt" @on-keyup="selectIssuePool">
                    <p slot="rtitle">评级机构池信息</p>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="selectIssuePool">查询</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" v-show="cutInfo === '本地'" @click="openInsertIssuePoolDialog" v-authCode.show="B_0157"
                            >新增</el-button
                        >
                    </span>

                    <span slot="button" class="dict-r-slot">
                        <el-button type="danger" size="mini" v-show="cutInfo === '本地'" @click="handleOpenRemoveDialog" v-authCode.show="B_0156"
                            >删除</el-button
                        >
                    </span>
                    <slot>
                        <el-table
                            :data="tableData"
                            border
                            size="mini"
                            style="width: 100%"
                            height="79vh"
                            max-height="720px"
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" width="55" size="mini" align="center"> </el-table-column>
                            <el-table-column prop="isGrOrCode" label="机构池编号"> </el-table-column>
                            <el-table-column prop="isGrOrName" label="机构池名称" show-overflow-tooltip> </el-table-column>
                            <el-table-column prop="dtCtDate" label="更新日期" show-overflow-tooltip align="center" sortable>
                                <template slot-scope="scope">
                                    <span>{{ dateFormat(scope.row.dtCtDate) }} {{ timeFormat(scope.row.dtCtTime) }}</span>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column prop="dtCtTime" label="更新时间" :formatter="formatterTime" align="center"> </el-table-column> -->
                            <el-table-column prop="dtCtUser" label="操作人" show-overflow-tooltip> </el-table-column>
                            <el-table-column label="操作" width="120">
                                <template slot-scope="scope">
                                    <RiskIconButton
                                        type="primary"
                                        icon="el-icon-edit"
                                        topTitle="编辑"
                                        v-authCode="B_0155"
                                        @on-click="openEditIssuePoolDialog(scope.row)"
                                    ></RiskIconButton>
                                    <RiskIconButton
                                        type="danger"
                                        icon="el-icon-delete"
                                        topTitle="删除"
                                        v-authCode="B_0156"
                                        @on-click="openRemoveIssuePoolDialog(scope.row)"
                                    ></RiskIconButton>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="issuePool" @page-change="currentChange"></risk-pagination>
                        </div>
                    </slot>
                </RiskRightModule>
                <!-- 新增 -->
                <yh-dialog drag title="新增评级机构池" :visible.sync="addDialog" width="400px" v-loading="loading">
                    <el-form label-width="140" size="mini">
                        <el-form-item label="机构池编号">
                            <el-input placeholder="自动生成" style="width: 220px" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="机构池名称">
                            <el-input style="width: 220px" maxlength="100" v-model="isGrOrName"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="mini" @click="addDialog = false"> 取 消 </el-button>
                        <el-button size="mini" type="primary" @click="insertIssuePool"> 确 定 </el-button>
                    </div>
                </yh-dialog>
                <!-- 编辑 -->
                <div>
                    <yh-dialog drag title="编辑评级机构池" :visible.sync="editDialog" width="400px" v-loading="loading">
                        <el-form label-width="140" size="mini">
                            <el-form-item label="评级机构池编号">
                                <el-input style="width: 220px" v-model="editIssuePool.isGrOrCode" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="评级机构池名称">
                                <el-input style="width: 220px" maxlength="100" v-model="editIssuePool.isGrOrName"></el-input>
                            </el-form-item>
                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="editDialog = false"> 取 消 </el-button>
                            <el-button size="mini" type="primary" @click="updateIssuePool"> 确 定 </el-button>
                        </div>
                    </yh-dialog>
                </div>
                <!-- 删除 -->
                <div>
                    <yh-dialog drag title="确认删除评级机构池？" :visible.sync="removeDialog" width="500px" v-loading="loading">
                        <div class="remove-text">
                            <span> {{ issuePoolCodeList.join(' , ') }}</span>
                        </div>
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="removeDialog = false"> 取 消 </el-button>
                            <el-button size="mini" type="primary" @click="removeIssuePool">确 定 </el-button>
                        </div>
                    </yh-dialog>
                </div>
            </template>

            <!-- 评级机构池/评级机构列表 -->
            <template v-else>
                <RiskRightModule v-model="person" :rightPlace="right2Place" :rightHeight="leftHgt">
                    <p slot="rtitle">评级机构池信息</p>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="searchIssues">查询</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="primary" size="mini" @click="queryAllIssueList" v-authCode.show="B_0158">编辑</el-button>
                    </span>
                    <span slot="button" class="dict-r-slot">
                        <el-button type="danger" size="mini" @click="handleOpenRemoveIssueDialog" v-authCode.show="B_0159">删除</el-button>
                    </span>
                    <slot>
                        <el-table
                            :data="issueData"
                            border
                            size="mini"
                            style="width: 100%"
                            height="79vh"
                            max-height="720px"
                            @selection-change="handleSelectionIssue"
                        >
                            <el-table-column type="selection" width="55" size="mini" align="center"> </el-table-column>
                            <el-table-column prop="issueCode" label="评级机构编号"> </el-table-column>
                            <el-table-column prop="issueName" label="评级机构名称" width="180" show-overflow-tooltip> </el-table-column>
                            <el-table-column prop="dtMdDate" label="更新日期" :formatter="formatterDate" align="center" sortable>
                                <template slot-scope="scope">
                                    <span>{{ dateFormat(scope.row.dtMdDate) }} {{ timeFormat(scope.row.dtMdTime) }}</span>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column prop="dtMdTime" label="更新时间" :formatter="formatterTime" align="center"> </el-table-column> -->
                            <el-table-column prop="dtMdUser" label="操作人"> </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="detail" @page-change="detailChange"></risk-pagination>
                        </div>
                    </slot>
                </RiskRightModule>
                <!-- 编辑机构池下的机构 -->
                <div>
                    <yh-dialog drag title="" :visible.sync="editIssueModal" width="800px" v-loading="loading">
                        <RiskTrantableInline
                            leftPlaceholder="编码/名称"
                            rightPlaceholder="编码/名称"
                            :columns="tranColumns"
                            :rightTableData="rightTranData"
                            :searchNames="['issueCode', 'issueName']"
                            indexKey="issueCode"
                            ref="tranTable"
                            sort="issueName"
                            url="/gradePool/issueGroup/allIssue"
                            v-if="editIssueModal"
                            style="min-height: 430px"
                        />
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="editIssueModal = false"> 取 消 </el-button>
                            <el-button size="mini" type="primary" @click="submitEditIssue">确 定 </el-button>
                        </div>
                    </yh-dialog>
                </div>
                <!-- 删除机构池下的机构 -->
                <div>
                    <yh-dialog drag title="确认删除评级机构池下发行人？" :visible.sync="removeIssueDialog" width="500px" v-loading="editLoading">
                        <div class="remove-text">
                            <span v-for="(item, index) in selectedIssueList" :key="index"> {{ item }} , </span>
                        </div>
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="removeIssueDialog = false"> 取 消 </el-button>
                            <el-button size="mini" type="primary" @click="removeIssue">确 定 </el-button>
                        </div>
                    </yh-dialog>
                </div>
            </template>
        </div>
    </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { formatter, formatterDate, formatterNumber, formatterTime, getCurrentPageData, timeFormat, dateFormat } from '@/utils/tools';

import RiskLeftModule from '@/common/components/risk-left-module.vue';
import RiskRightModule from '@/common/components/risk-right-module.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTrantableInline from '@/common/components/risk-trantable-inline.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'GradeIssue',
    components: {
        RiskLeftModule,
        RiskRightModule,
        RiskIconButton,
        RiskTrantableInline,
        RiskPagination,
    },
})
export default class GradeIssue extends Vue {
    formatterDate = formatterDate;
    formatterTime = formatterTime;
    formatter = formatter;
    formatterNumber = formatterNumber;
    dateFormat = dateFormat;
    timeFormat = timeFormat;
    private userValue: string = '';
    private ltitleName: string = '编号/名称';
    private leftHgt: string = '100vh';
    private rtitleName: string = '机构池编号/名称';
    private right2Place: string = '机构编号/名称';
    private roleInput: string = '';

    private person: string = '';

    private loading: boolean = false;

    private treeData: any = [
        {
            label: '本地',
            id: 1,
            children: [],
        },
        {
            label: '外部',
            id: 2,
            children: [],
        },
    ];
    private cutInfo: string = '外部';
    private defaultExpandedKeys: any[] = [2];

    private issuePool: pages = {
        total: 0,
        pageSize: 25,
        currentPage: 1,
    };
    private detail: pages = {
        total: 0,
        pageSize: 25,
        currentPage: 1,
    };

    private tableDisk: any[] = [];
    private tableSans: any[] = [];
    private tableDiskList: any[] = [];
    private tableSansList: any[] = [];
    private tableData: any[] = [];
    private issueData: any[] = [];
    private groupCode: string = ''; // 当前选中的评级机构池

    private issueDataList: any[] = []; // 已选中的机构

    private issuePoolCodeList: any[] = [];

    private issueCodeList: any[] = [];

    private selectedIssueList: any[] = []; // 要删除的发行人

    // private issuePoolCode: string = '';

    private rightTranData: any[] = [];

    private addDialog: boolean = false;
    private editDialog: boolean = false;
    private removeDialog: boolean = false;

    private editIssueModal: boolean = false; // 编辑弹窗

    private removeIssueDialog: boolean = false;
    private isGrOrName: string = ''; // 评级机构池名称

    private editIssuePool = {
        isGrOrCode: '',
        isGrOrName: '',
    };
    private selectList: any[] = [];

    // 穿梭框数据
    private tranColumns: any[] = [
        {
            label: '编号',
            prop: 'issueCode',
            width: 80,
        },
        {
            label: '名称',
            prop: 'issueName',
        },
    ];

    private issueDataLists: any[] = []; // 全部发行人

    mounted() {
        this.queryIssuePoolInfo();
    }

    // 左边查询
    private submitInput(): void {}

    // 左边栏选择节点
    private clickNode(data: any): void {
        this.cutInfo = data.label;
        this.groupCode = data.id;
        // 重置节点数据
        this.queryIssueInfo(this.groupCode);
        if (this.cutInfo == '本地') {
            this.issuePool.total = this.tableDisk.length;
            this.tableData = this.tableDisk;
        } else if (this.cutInfo == '外部') {
            this.tableData = this.tableSans;
            this.issuePool.total = this.tableSans.length;
        }
    }

    // 查询评级机构池
    private selectIssuePool(): void {
        if (this.cutInfo === '本地') {
            this.tableDisk = this.handleFilter(this.tableDiskList, this.roleInput);
            this.issuePool.total = this.tableDisk.length;
            this.tableData = getCurrentPageData(this.tableDisk, this.issuePool.currentPage, this.issuePool.pageSize);
        } else {
            this.tableSans = this.handleFilter(this.tableSansList, this.roleInput);
            this.issuePool.total = this.tableSans.length;
            this.tableData = getCurrentPageData(this.tableSans, this.issuePool.currentPage, this.issuePool.pageSize);
        }
    }

    // 评级机构池筛选数据
    private handleFilter(dataSource: any, param: any): any {
        if (!param || !dataSource) {
            return dataSource;
        } else {
            return dataSource.filter(
                (item: any) =>
                    (item.isGrOrName || '').toUpperCase().includes(param.toUpperCase()) ||
                    (item.isGrOrCode || '').toUpperCase().includes(param.toUpperCase())
            );
        }
    }

    // 查询评级机构信息
    private searchIssues(): void {
        this.issueDataList = this.detailFileter(this.issueDataLists, this.person);
        this.detail.total = this.issueDataList.length;
        this.issueData = getCurrentPageData(this.issueDataList, this.detail.currentPage, this.detail.pageSize);
    }

    // 评级机构过滤数据
    private detailFileter(dataSource: any, param: any): any {
        if (!param || !dataSource) {
            return dataSource;
        } else {
            return dataSource.filter(
                (item: any) =>
                    (item.issueCode || '').toUpperCase().includes(param.toUpperCase()) ||
                    (item.issueName || '').toUpperCase().includes(param.toUpperCase())
            );
        }
    }

    // 评级机构池分页
    private currentChange(): void {
        if (this.cutInfo == '本地') {
            this.issuePool.total = this.tableDisk.length;
            this.tableData = getCurrentPageData(this.tableDisk, this.issuePool.currentPage, this.issuePool.pageSize);
        } else {
            this.issuePool.total = this.tableSans.length;
            this.tableData = getCurrentPageData(this.tableSans, this.issuePool.currentPage, this.issuePool.pageSize);
        }
    }

    // 获取评级机构池数据
    private queryIssuePoolInfo(): void {
        this.$axios.get('gradePool/issueGroup/all').then((res: any) => {
            var local = [];
            var outside = [];
            let disk = [];
            let Sans = [];

            for (let item of res) {
                if (item.sourceType === '1') {
                    disk.push(item);
                    let datas = item.isGrOrCode + '-' + item.isGrOrName;
                    local.push({ label: datas, id: item.isGrOrCode });
                } else {
                    Sans.push(item);
                    let datas = item.isGrOrCode + '-' + item.isGrOrName;
                    outside.push({ label: datas, id: item.isGrOrCode });
                }
            }
            this.treeData[0].children = local;
            this.treeData[1].children = outside;
            this.tableDisk = disk;
            this.tableSans = Sans;
            this.tableDiskList = disk;
            this.tableSansList = Sans;
            this.issuePool.currentPage = 1;
            this.currentChange();
        });
    }

    // 新增评级机构池弹框
    openInsertIssuePoolDialog() {
        this.isGrOrName = '';
        this.addDialog = true;
    }

    // 新增评级机构池
    private insertIssuePool() {
        if (!this.isGrOrName) {
            this.yh_message_error('评级机构池名称不能为空！');
            return;
        }
        this.$axios
            .post('gradePool/issueGroup/insert/isGroup', {
                isGrOrCode: '自动生成',
                isGrOrName: this.isGrOrName,
            })
            .then((res: any) => {
                this.isGrOrName = '';
                this.yh_message_success('新增成功');
                this.queryIssuePoolInfo();
                this.addDialog = false;
            });
    }

    // 编辑评级机构池弹框
    private openEditIssuePoolDialog(row: any): void {
        this.editIssuePool = JSON.parse(JSON.stringify(row));
        this.editDialog = true;
    }

    // 编辑评级机构池
    private updateIssuePool() {
        if (!this.editIssuePool.isGrOrName) {
            this.yh_message_error('评级机构池名称不能为空！');
            return;
        }
        this.$axios({
            url: 'gradePool/issueGroup/update',
            method: 'put',
            data: this.editIssuePool,
        }).then((res: any) => {
            this.yh_message_success('更新成功');
            this.queryIssuePoolInfo();
            this.editDialog = false;
        });
    }

    // 判断是否选择机构池
    private handleOpenRemoveDialog(): void {
        this.issuePoolCodeList = [];
        for (var i in this.selectList) {
            this.issuePoolCodeList.push(this.selectList[i].isGrOrCode);
        }
        if (!this.issuePoolCodeList || this.issuePoolCodeList.length < 1) {
            this.yh_message_warn('请选择删除的机构池');
            return;
        }
        this.removeDialog = true;
    }

    // 选择机构池
    private handleSelectionChange(val: any): void {
        this.selectList = val;
        this.issuePoolCodeList = [];
        for (var i in val) {
            this.issuePoolCodeList.push(val[i].isGrOrCode);
        }
    }

    // 单个删除机构池弹框
    private openRemoveIssuePoolDialog(row: any): void {
        this.removeDialog = true;
        this.issuePoolCodeList = [];
        this.issuePoolCodeList.push(row.isGrOrCode);
    }

    // 删除评级机构池
    private removeIssuePool() {
        this.loading = true;
        this.$axios({
            url: '/gradePool/issueGroup/delete',
            method: 'DELETE',
            data: this.issuePoolCodeList,
        })
            .then(res => {
                this.loading = false;
                this.removeDialog = false;
                this.queryIssuePoolInfo();
                this.yh_message_success('删除成功');
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 获取评级机构数据
    private queryIssueInfo(groupCode: string) {
        this.$axios.get('gradePool/issueGroup/issueList/' + groupCode).then((res: any) => {
            if (res) {
                this.issueDataLists = res;
                let resList = res;
                for (let i = 0; i < resList.length; i++) {
                    resList[i].id = resList[i].issueCode;
                }
                this.issueDataList = res;
                this.rightTranData = res;
                this.detail.currentPage = 1;
                this.detailChange();
            }
        });
    }

    private detailChange(): void {
        this.detail.total = this.issueDataList.length;
        this.issueData = getCurrentPageData(this.issueDataList, this.detail.currentPage, this.detail.pageSize);
    }

    // 获取所有发行人
    private queryAllIssueList(): void {
        this.editIssueModal = true;
        this.rightTranData = this.issueDataLists;

        // this.rightTranData = JSON.parse(JSON.stringify(this.issueDataLists));

        // this.$axios
        //     .post('/gradePool/issueGroup/allIssue', {
        //         paging: {
        //             currentPage: 1,
        //             pageSize: 25,
        //         },
        //         keyName: '',
        //         filterCodes: this.issueDataLists.map((item: any) => item.issueCode),
        //     })
        //     .then((res: any) => {
        //         let a = res.list;
        //         for (let i = 0; i < a.length; i++) {
        //             a[i].id = a[i].issueCode;
        //         }
        //         this.leftTranData = a;
        //     });
    }

    // 获取选中的发行人
    private handleSelectionIssue(val: any): void {
        this.selectedIssueList = [];
        for (var i in val) {
            this.selectedIssueList.push(val[i].issueCode);
        }
    }

    // 删除评级机构下的发行人弹框显示
    private handleOpenRemoveIssueDialog(): void {
        if (!this.selectedIssueList || this.selectedIssueList.length < 1) {
            this.yh_message_warn('未选择删除项');
            return;
        }
        this.removeIssueDialog = true;
    }

    // 删除评级机构池下的发行人
    private removeIssue() {
        this.loading = true;
        this.$axios({
            url: '/gradePool/issueGroup/delete/issue/' + this.groupCode,
            method: 'DELETE',
            data: this.selectedIssueList,
        })
            .then(res => {
                this.loading = false;
                this.removeIssueDialog = false;
                this.queryIssueInfo(this.groupCode);
                this.yh_message_success('删除成功');
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 确认评级机构池下的发行人
    private submitEditIssue() {
        this.issueCodeList = [];
        const rightData = (this.$refs.tranTable as any).getRightAllData();
        rightData.map((item: any) => {
            this.issueCodeList.push(item.issueCode);
        });
        this.$axios.post('/gradePool/issueGroup/insert/isGroup/issue/' + this.groupCode, this.issueCodeList).then(res => {
            // this.loading = false;
            this.editIssueModal = false;
            this.yh_message_success('更新成功');
            this.queryIssueInfo(this.groupCode);
        });
        // .catch(() => {
        //   this.loading = false;
        // });
    }
}
</script>
<style lang="scss" scoped>
.issue-list {
    height: 100%;
}
.dict-r-slot {
    margin-left: 10px;
}
/deep/.el-dialog {
    margin-top: 10vh !important;
    .el-dialog__body {
        max-height: 90vh;
        padding: 10px;
    }
}
/deep/ .el-table--border th:first-child .cell {
    padding-left: 6px;
}
</style>
